/**
 * HTML代码管理表单页面
 * 用于创建和编辑HTML代码，包含HTML代码编辑器
 * 使用项目统一的UI组件保持界面一致性
 */

import React, { useState, useEffect } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { 
  useHtmlCode, 
  useCreateHtmlCode, 
  useUpdateHtmlCode,
  useUpdateHtmlContent,
  useValidateHtmlCode
} from '../../lib/api/hooks/use-api.js';
import { Container } from '@/components/common/container';
import { Toolbar, ToolbarActions, ToolbarHeading } from '@/layouts/demo1/components/toolbar';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Label } from '@/components/ui/label';
import { Badge } from '@/components/ui/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { ArrowLeft, Save, Eye, Code, FileText, CheckCircle, AlertCircle } from 'lucide-react';
import HtmlPreview from '@/components/html-preview/html-preview';
import ProfessionalHtmlEditor from '@/components/code-editor/professional-html-editor';

/**
 * HTML代码管理表单页面组件
 * 支持创建和编辑HTML代码，包含代码编辑器和预览功能
 */
const HtmlCodeFormPage = () => {
  // 路由相关
  const navigate = useNavigate();
  const { id } = useParams(); // 获取URL参数中的ID
  const isEdit = !!id; // 判断是否为编辑模式

  // 表单数据状态
  const [formData, setFormData] = useState({
    name: '', // 页面名称
    workspace_id: '', // 工作空间ID
    page_id: '', // 页面ID
    app_id: '', // 应用ID
    content: '', // 内容描述
    page: '', // HTML代码内容
  });

  // 表单验证状态
  const [errors, setErrors] = useState({});
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [activeTab, setActiveTab] = useState('form'); // 当前激活的标签页

  // 获取HTML代码详情（编辑模式）
  const { 
    data: htmlCodeData, 
    isLoading: isLoadingDetail,
    error: detailError 
  } = useHtmlCode(id, {
    enabled: isEdit && !!id
  });

  // 创建HTML代码的变更操作
  const createHtmlCodeMutation = useCreateHtmlCode({
    onSuccess: (data) => {
      navigate(`/html-code-management/detail/${data.id}`);
    },
    onError: (error) => {
      console.error('创建HTML代码失败:', error);
      setIsSubmitting(false);
    }
  });

  // 更新HTML代码的变更操作
  const updateHtmlCodeMutation = useUpdateHtmlCode({
    onSuccess: (data) => {
      navigate(`/html-code-management/detail/${data.id}`);
    },
    onError: (error) => {
      console.error('更新HTML代码失败:', error);
      setIsSubmitting(false);
    }
  });

  // 更新HTML内容的变更操作
  const updateHtmlContentMutation = useUpdateHtmlContent({
    onSuccess: (data) => {
      console.log('HTML内容更新成功');
    },
    onError: (error) => {
      console.error('更新HTML内容失败:', error);
    }
  });

  // 验证HTML代码的变更操作
  const validateHtmlCodeMutation = useValidateHtmlCode();

  // 当获取到详情数据时，填充表单
  useEffect(() => {
    if (htmlCodeData && isEdit) {
      setFormData({
        name: htmlCodeData.name || '',
        workspace_id: htmlCodeData.workspace_id || '',
        page_id: htmlCodeData.page_id || '',
        app_id: htmlCodeData.app_id || '',
        content: htmlCodeData.content || '',
        page: htmlCodeData.page || '',
      });
    }
  }, [htmlCodeData, isEdit]);

  // 处理表单字段变化
  const handleInputChange = (field, value) => {
    setFormData(prev => ({
      ...prev,
      [field]: value
    }));
    
    // 清除该字段的错误信息
    if (errors[field]) {
      setErrors(prev => ({
        ...prev,
        [field]: null
      }));
    }
  };

  // 表单验证
  const validateForm = () => {
    const newErrors = {};

    if (!formData.name.trim()) {
      newErrors.name = '页面名称不能为空';
    }

    if (!formData.page.trim()) {
      newErrors.page = 'HTML代码内容不能为空';
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  // 处理表单提交
  const handleSubmit = async (e) => {
    e.preventDefault();
    
    if (!validateForm()) {
      return;
    }

    setIsSubmitting(true);

    try {
      if (isEdit) {
        // 编辑模式：更新HTML代码
        await updateHtmlCodeMutation.mutateAsync({
          id: id,
          data: formData
        });
      } else {
        // 创建模式：创建新的HTML代码
        await createHtmlCodeMutation.mutateAsync(formData);
      }
    } catch (error) {
      console.error('提交失败:', error);
      setIsSubmitting(false);
    }
  };

  // 处理HTML代码验证
  const handleValidateHtml = async () => {
    if (!formData.page.trim()) {
      return;
    }

    try {
      const result = await validateHtmlCodeMutation.mutateAsync(formData.page);
      if (result.valid) {
        alert('HTML代码验证通过！');
      } else {
        alert(`HTML代码验证失败：${result.errors?.join(', ') || '未知错误'}`);
      }
    } catch (error) {
      console.error('验证失败:', error);
      alert('验证失败，请检查网络连接');
    }
  };

  // 处理返回
  const handleBack = () => {
    navigate('/html-code-management');
  };

  // 处理预览
  const handlePreview = () => {
    if (!formData.page.trim()) {
      alert('请先输入HTML代码');
      return;
    }
    setActiveTab('preview');
  };

  // 渲染HTML预览
  const renderHtmlPreview = () => (
    <HtmlPreview
      htmlContent={formData.page}
      title="HTML预览"
      showStats={true}
      showControls={true}
    />
  );

  // 渲染表单字段
  const renderFormField = (field, label, type = 'text', options = {}) => {
    const hasError = !!errors[field];
    
    return (
      <div className="space-y-2">
        <Label htmlFor={field} className="text-sm font-medium">
          {label}
          {options.required && <span className="text-destructive ml-1">*</span>}
        </Label>
        {type === 'textarea' ? (
          <Textarea
            id={field}
            value={formData[field]}
            onChange={(e) => handleInputChange(field, e.target.value)}
            placeholder={options.placeholder}
            className={hasError ? 'border-destructive' : ''}
            rows={options.rows || 3}
          />
        ) : type === 'select' ? (
          <Select
            value={formData[field] || 'none'}
            onValueChange={(value) => handleInputChange(field, value === 'none' ? '' : value)}
          >
            <SelectTrigger className={hasError ? 'border-destructive' : ''}>
              <SelectValue placeholder={options.placeholder} />
            </SelectTrigger>
            <SelectContent>
              {options.options?.map((option) => (
                <SelectItem key={option.value} value={option.value}>
                  {option.label}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        ) : (
          <Input
            id={field}
            type={type}
            value={formData[field]}
            onChange={(e) => handleInputChange(field, e.target.value)}
            placeholder={options.placeholder}
            className={hasError ? 'border-destructive' : ''}
          />
        )}
        {hasError && (
          <p className="text-sm text-destructive">{errors[field]}</p>
        )}
      </div>
    );
  };

  // 加载状态
  if (isEdit && isLoadingDetail) {
    return (
      <Container>
        <div className="text-center py-8">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto"></div>
          <p className="mt-2 text-muted-foreground">加载中...</p>
        </div>
      </Container>
    );
  }

  // 错误状态
  if (isEdit && detailError) {
    return (
      <Container>
        <div className="text-center py-8">
          <AlertCircle className="size-12 text-destructive mx-auto mb-4" />
          <p className="text-destructive">加载失败: {detailError.message}</p>
          <Button variant="outline" onClick={handleBack} className="mt-4">
            返回列表
          </Button>
        </div>
      </Container>
    );
  }

  return (
    <>
      {/* 页面标题和操作栏 */}
      <Container>
        <Toolbar>
          <ToolbarHeading
            title={isEdit ? '编辑页面对象' : '新建页面对象'}
            description={isEdit ? '修改页面对象信息和内容' : '创建新的页面对象'}
          />
          <ToolbarActions>
            <Button variant="outline" onClick={handleBack}>
              <ArrowLeft className="size-4 me-2" />
              返回列表
            </Button>
          </ToolbarActions>
        </Toolbar>
      </Container>

      {/* 表单内容 */}
      <Container>
        <Tabs value={activeTab} onValueChange={setActiveTab}>
          <TabsList className="grid w-full grid-cols-3">
            <TabsTrigger value="form" className="flex items-center gap-2">
              <FileText className="size-4" />
              基本信息
            </TabsTrigger>
            <TabsTrigger value="code" className="flex items-center gap-2">
              <Code className="size-4" />
              页面代码
            </TabsTrigger>
            <TabsTrigger value="preview" className="flex items-center gap-2">
              <Eye className="size-4" />
              预览
            </TabsTrigger>
          </TabsList>

          {/* 基本信息标签页 */}
          <TabsContent value="form" className="space-y-6">
            <Card>
              <CardHeader>
                <CardTitle>基本信息</CardTitle>
              </CardHeader>
              <CardContent className="space-y-6">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  {renderFormField('name', '页面名称', 'text', {
                    required: true,
                    placeholder: '请输入页面名称'
                  })}
                  
                  {renderFormField('workspace_id', '工作空间', 'select', {
                    placeholder: '选择工作空间',
                    options: [
                      { value: 'none', label: '请选择工作空间' },
                      { value: 'workspace1', label: '工作空间1' },
                      { value: 'workspace2', label: '工作空间2' },
                      { value: 'workspace3', label: '工作空间3' },
                    ]
                  })}
                  
                  {renderFormField('page_id', '页面ID', 'text', {
                    placeholder: '请输入页面ID'
                  })}
                  
                  {renderFormField('app_id', '应用程序', 'select', {
                    placeholder: '选择应用程序',
                    options: [
                      { value: 'none', label: '请选择应用' },
                      { value: 'app1', label: '应用1' },
                      { value: 'app2', label: '应用2' },
                      { value: 'app3', label: '应用3' },
                    ]
                  })}
                </div>
                
                {renderFormField('content', '内容描述', 'textarea', {
                  placeholder: '请输入内容描述',
                  rows: 4
                })}
              </CardContent>
            </Card>
          </TabsContent>

          {/* HTML代码标签页 */}
          <TabsContent value="code" className="space-y-6 w-full overflow-hidden">
            <div className="space-y-4 w-full">
              {/* HTML代码编辑器 */}
              <ProfessionalHtmlEditor
                value={formData.page}
                onChange={(value) => handleInputChange('page', value)}
                placeholder="请输入页面对象代码..."
                showControls={true}
                onPreview={handlePreview}
                onValidate={handleValidateHtml}
                className={errors.page ? 'border-destructive' : ''}
              />
              
              {/* 错误提示 */}
              {errors.page && (
                <div className="text-sm text-destructive bg-destructive/10 p-3 rounded-md">
                  {errors.page}
                </div>
              )}
              
              {/* 操作按钮 */}
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-2">
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={handleValidateHtml}
                    disabled={!formData.page.trim() || validateHtmlCodeMutation.isPending}
                  >
                    {validateHtmlCodeMutation.isPending ? (
                      <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-current"></div>
                    ) : (
                      <CheckCircle className="size-4 me-2" />
                    )}
                    验证代码
                  </Button>
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={handlePreview}
                  >
                    <Eye className="size-4 me-2" />
                    预览
                  </Button>
                </div>
              </div>
            </div>
          </TabsContent>

          {/* 预览标签页 */}
          <TabsContent value="preview" className="space-y-6">
            <Card>
              <CardHeader>
                <CardTitle>HTML预览</CardTitle>
              </CardHeader>
              <CardContent>
                {renderHtmlPreview()}
              </CardContent>
            </Card>
          </TabsContent>
        </Tabs>

        {/* 提交按钮 */}
        <div className="flex items-center justify-end gap-4 pt-6 border-t">
          <Button variant="outline" onClick={handleBack}>
            取消
          </Button>
          <Button 
            onClick={handleSubmit}
            disabled={isSubmitting}
          >
            {isSubmitting ? (
              <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-current me-2"></div>
            ) : (
              <Save className="size-4 me-2" />
            )}
            {isEdit ? '更新' : '创建'}
          </Button>
        </div>
      </Container>
    </>
  );
};

export default HtmlCodeFormPage;